package game;

import java.util.ArrayList;

import utility.Chess;
import utility.Piece;
import utility.Position;
import utility.Utility_Game;
import android.content.Context;
import android.content.res.Resources;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.os.Bundle;
import android.util.Log;
import android.view.MotionEvent;
import android.view.SurfaceHolder;
import coganh.Activity.R;

public class GameThread extends Thread {

	public static final int DIFFICULTY_EASY = 0;
	public static final int DIFFICULTY_HARD = 1;
	public static final int DIFFICULTY_MEDIUM = 2;

	public static final int STATE_LOSE = 1;
	public static final int STATE_PAUSE = 2;
	public static final int STATE_READY = 3;
	public static final int STATE_RUNNING = 4;
	public static final int STATE_WIN = 5;

	private static final String KEY_DIFFICULTY = "mDifficulty";
	private static final String KEY_WINS = "mWinsInARow";

<<<<<<< .mine
	private ArrayList<GameSprite> mSprites; // visible sprite
	private ArrayList<GameSprite> mSpritestoRemove; // sprite to remove
	private ArrayList<Piece> mPieces;// trang thai ban co
	private ArrayList<Piece> mPiecesToRemove;
	private ArrayList<Piece> mPiecesToMove;
	private ArrayList<Piece> mPiecesDest;
=======
	private ArrayList<GameSprite> mSprites; // visible sprite
	private ArrayList<GameSprite> mSpritestoRemove; // sprite to remove
>>>>>>> .r17

	// xu ly touch
	private ArrayList<Position> mPoDest;
	private Piece pieceSelect;

	private int mDifficulty;

	private int mState;// trang thai game

	/** Dung de xat dinh delay giua 2 lan ve ke tiep nhau cua 1 sprite */
	private long mLastTime;

	private boolean mRun = false;

	/** dung de tuong tac */
	private SurfaceHolder mSurfaceHolder;

	private Paint textPaint;

	/** Number of sprites drawed in a row. */
	private int numSprites;

	private Resources res;
	private Context mContext;
<<<<<<< .mine

=======
	@SuppressWarnings("unused")
	private Alpha_Beta mAlpha_Beta;

>>>>>>> .r17
	private Chess mchChessBoard, mBackground, mChess;
	private ArrayList<Position> mPositions;
<<<<<<< .mine
=======
	private ArrayList<Item> mItems; // tap hop cac quan co tren ban co (16 quan)
									// item la quan co logic
									// mchess la quan co vat ly
	private ArrayList<Item> mItemsToMove;
	private ArrayList<Item> mItemsDest;
>>>>>>> .r17

	public GameThread(SurfaceHolder surfaceHolder, Context context) {
		// get handles to some important objects
		mSurfaceHolder = surfaceHolder;
		mContext = context;

		res = context.getResources();

		mSprites = new ArrayList<GameSprite>();
		mSpritestoRemove = new ArrayList<GameSprite>();
<<<<<<< .mine

		mPiecesDest = new ArrayList<Piece>();
		mPiecesToRemove = new ArrayList<Piece>();
		mPiecesToMove = new ArrayList<Piece>();

=======

		mItemsDest = new ArrayList<Item>();
		mItemsToMove = new ArrayList<Item>();

>>>>>>> .r17
		mChess = new Chess();
		mChess.setHeight(40);
		mChess.setWidth(40);

		// xu ly touch
		mPoDest = new ArrayList<Position>();

		initBackGround();
		initChessBoard();
		InitPosition(mchChessBoard);
		InitItems();

		textPaint = new Paint();
		textPaint.setARGB(255, 255, 255, 255);
		textPaint.setTextSize(16);

		numSprites = 0;
		mDifficulty = DIFFICULTY_MEDIUM;
	}

	@Override
	public void run() {
		while (mRun) {
			Canvas c = null;
			try {
				c = mSurfaceHolder.lockCanvas(null);
				synchronized (mSurfaceHolder) {
					if (mState == STATE_RUNNING)
						updatePhysics();
					doDraw(c);
				}
			} catch (Exception e) {
				System.out.println(e.getStackTrace());
			} finally {
				if (c != null) {
					mSurfaceHolder.unlockCanvasAndPost(c);
				}
			}
		}
	}

	/**
	 * Draws to the provided Canvas.
	 */
	private void doDraw(Canvas canvas) {
		// canvas.drawColor(Color.BLACK);
		mBackground.draw(canvas);
		mchChessBoard.draw(canvas);
		Bitmap bmdest = BitmapFactory.decodeResource(res, R.drawable.move);

		for (GameSprite a : mSprites) {
			a.draw(canvas);
		}
<<<<<<< .mine

		for (Piece p : mPieces) {
			p.draw(canvas);
		}
=======
		for (Item i : mItems)
			if (i.getIndex() == 1)
				canvas.drawBitmap(
						bmblue,
						mPositions.get(
								5 * i.getCurrentRow() + i.getCurrentCol())
								.getxPost() - 20,
						mPositions.get(
								5 * i.getCurrentRow() + i.getCurrentCol())
								.getyPost() - 20, null);
			else
				canvas.drawBitmap(
						bmred,
						mPositions.get(
								5 * i.getCurrentRow() + i.getCurrentCol())
								.getxPost() - 20,
						mPositions.get(
								5 * i.getCurrentRow() + i.getCurrentCol())
								.getyPost() - 20, null);
		for (Item i : mItemsDest)
			canvas.drawBitmap(bmdest,
					mPositions.get(5 * i.getCurrentRow() + i.getCurrentCol())
							.getxPost() - 15,
					mPositions.get(5 * i.getCurrentRow() + i.getCurrentCol())
							.getyPost() - 15, null);
>>>>>>> .r17
		for (Piece p : mPiecesDest) {
			p.draw(canvas);
			// Log.d("dest", "[" + p.getmPosition().getX() + "]" + "["
			// +p.getmPosition().getY()
			// + "]");
		}

		canvas.restore();
	}

	private void updatePhysics() {
		long now = System.currentTimeMillis();
		// Khong lam gi het neu mLastTime dang chi den mot thoi diem trong tuong
		// lai
		// Cho phep game-start tri hoan 100ms
		if (mLastTime > now)
			return;

		synchronized (mSprites) {
			for (GameSprite a : mSprites) {
				a.Update(now);

				if (a.isDispose())
					mSpritestoRemove.add(a);
			}
		}

		synchronized (mSpritestoRemove) {
			mSprites.removeAll(mSpritestoRemove);
			mSpritestoRemove.clear();
		}

		numSprites = mSprites.size();
		mLastTime = now;
	}

	/**
	 * Detected touch event
	 * 
	 * @param event
	 */
	public void doTouch(MotionEvent event) {

		int action = event.getAction();
		float x = event.getX(); // or getRawX();
		float y = event.getY();
		if (action == MotionEvent.ACTION_DOWN) {
<<<<<<< .mine
			Position mPo = Utility_Game.getPosition(mPositions, mChess, x, y);
=======
			Position mPo = Utility_Game.getPosition(x, y, mChess, mPositions);
>>>>>>> .r17
			if (mPo != null) {
				Log.d("le duc hien", "[" + mPo.getX() + "]" + "[" + mPo.getY()
						+ "]");
<<<<<<< .mine
				// touch vao 1 vi tri tren ban co
				// 3 truong hop xay ra
				// 1. touch vao quan co
				// 2. touch vao 1 phan tu cua destlist
				// 3. touch vao 1 vi tri khong co quan co nao
				pieceSelect = Utility_Game.getPieceByPosition(mPieces, mPo);
				// xu ly truong hop 1
				// tao dest list, piece destlist
				if (pieceSelect != null) {
					mPoDest.clear();
					mPoDest.addAll(Utility_Game.getDest(mPieces, mPositions,
							pieceSelect));

					ArrayList<Piece> mpiecesTemp = new ArrayList<Piece>();
					for (Piece pi : mPieces) {
						Piece tpi = new Piece(pi);
						mpiecesTemp.add(tpi);
					}
					for (Piece pi : mpiecesTemp) {
						if (pi.compare(pieceSelect)) {
							mPieces.get(mpiecesTemp.indexOf(pi)).setState(
									Piece.STATECHESS_ACTIVE);
						} else
							mPieces.get(mpiecesTemp.indexOf(pi)).setState(
									Piece.STATECHESS_NOMAL);
					}

					Log.d("so luong dest", "" + mPoDest.size());
					// ve hinh dest len ban co
					if (!mPoDest.isEmpty()) {
						mPiecesDest.clear();
						for (Position po : mPoDest) {
							Piece destpiece = new Piece();
							Bitmap bitmap = BitmapFactory.decodeResource(res,
									R.drawable.move);
							destpiece.Initialize(bitmap, 30, 30, 24, 1, true);
							destpiece.setPosition(po);
							mPiecesDest.add(destpiece);
						}
					}
				}

				// xu ly truogn hop 2.
				// touch vao 1 vi tri tren destlist
				else if (!mPoDest.isEmpty()) {
					Log.d("12312343", "dfhdfghfghdfghfghfhfg");
					ArrayList<Piece> mpiecesTemp = new ArrayList<Piece>();
					for (Piece pi : mPieces) {
						Piece tpi = new Piece(pi);
						mpiecesTemp.add(tpi);
					}
					for (Position po : mPoDest) {
						if (po.compare(mPo)) {
							// xu ly di chuyen quan co
							for (Piece pi : mpiecesTemp) {
								if (pi.getState() == Piece.STATECHESS_ACTIVE) {
									mPieces.get(mpiecesTemp.indexOf(pi))
											.setState(Piece.STATECHESS_NOMAL);
									mPieces.get(mpiecesTemp.indexOf(pi)).move(
											mPo);
									break;
								}
								Log.d("12312343", "" + pi.getState());
							}
						}
					}
					// xoa destlist
					mPoDest.clear();
					mPiecesDest.clear();
				}
=======
				// touch vao 1 vi tri tren ban co
				Item temp = Utility_Game
						.getItem(mItems, mPo.getX(), mPo.getY());
				if (temp != null) {
					for (Item i : mItems) {
						// touch vao 1 quan co
						// chi tinh quan co duoc touch cuoi cung
						if (i.getCurrentCol() == mPo.getY()
								&& i.getCurrentRow() == mPo.getX()) {
							Log.d("mItems size", "" + mItems.size());
							mItemsToMove.clear();
							mItemsDest.clear();
							mItemsToMove.add(i);
							mItemsDest = Utility_Game.getItemsDest(mItems,
									i.getCurrentRow(), i.getCurrentCol());
							Log.d("mItemDest size", "" + mItemsDest.size());

						}
					}
				} else if (!mItemsDest.isEmpty()) {
					for (Item i : mItemsDest) {
						if (i.getCurrentCol() == mPo.getY()
								&& i.getCurrentRow() == mPo.getX()) {
							mItems.removeAll(mItemsToMove);
						}
					}
					mItemsDest.clear();
					mItemsToMove.clear();
				} else {
					mItemsDest.clear();
					mItemsToMove.clear();
				}
			} else {
				mItemsDest.clear();
				mItemsToMove.clear();
>>>>>>> .r17
			}
			Log.d("mItem size", "" + mItems.size());
		}
	}

	private void InitPosition(Chess chess) {

		mPositions = new ArrayList<Position>();
		mPositions.addAll(Utility_Game.InitPosition(chess));
	}

	/**
	 * Sets the game mode. That is, whether we are running, paused, in the
	 * failure state, in the victory state, etc.
	 * 
	 * @param mode
	 *            one of the STATE_* constants
	 * @param message
	 *            string to add to screen or null
	 */
	public void setState(int mode, CharSequence message) {
		synchronized (mSurfaceHolder) {
			mState = mode;
			if (mState == STATE_RUNNING) {
				// Message msg = mGameView.obtainMessage();
				// Bundle b = new Bundle();
				// b.putString("text", "");
				// b.putInt("viz", View.INVISIBLE);
				// msg.setData(b);
				// mGameView.sendMessage(msg);
			} else {

				Resources res = mContext.getResources();
				CharSequence str = "";
				if (mState == STATE_READY)
					str = res.getText(R.string.mode_ready);
				else if (mState == STATE_PAUSE)
					str = res.getText(R.string.mode_pause);
				else if (mState == STATE_LOSE)
					str = res.getText(R.string.mode_lose);
				else if (mState == STATE_WIN)
					str = res.getString(R.string.mode_win_prefix) + numSprites
							+ " " + res.getString(R.string.mode_win_suffix);

				if (message != null) {
					str = message + "\n" + str;
				}

				if (mState == STATE_LOSE)
					numSprites = 0;

				// Message msg = mGameView.obtainMessage();
				// Bundle b = new Bundle();
				// b.putString("text", str.toString());
				// b.putInt("viz", View.VISIBLE);
				// msg.setData(b);
				// mGameView.sendMessage(msg);
			}
		}
	}

	/**
	 * Dump game state to the provided Bundle. Typically called when the
	 * Activity is being suspended.
	 * 
	 * @return Bundle with this view's state
	 */
	public Bundle saveState(Bundle map) {
		synchronized (mSurfaceHolder) {
			if (map != null) {
				map.putInt(KEY_DIFFICULTY, Integer.valueOf(mDifficulty));
				map.putInt(KEY_WINS, Integer.valueOf(numSprites));
			}
		}
		return map;
	}

	/**
	 * Sets the current difficulty.
	 * 
	 * @param difficulty
	 */
	public void setDifficulty(int difficulty) {
		synchronized (mSurfaceHolder) {
			mDifficulty = difficulty;
		}
	}

	public void setRunning(boolean b) {
		mRun = b;
	}

	public void setState(int mode) {
		synchronized (mSurfaceHolder) {
			setState(mode, null);
		}
	}

	/* Callback invoked when the surface dimensions change. */
	public void setSurfaceSize(int width, int height) {
		// synchronized to make sure these all change atomically
		synchronized (mSurfaceHolder) {
		}
	}

	/**
	 * Resumes from a pause.
	 */
	public void unpause() {
		// Move the real time clock up to now
		synchronized (mSurfaceHolder) {
			mLastTime = System.currentTimeMillis() + 100;
		}
		setState(STATE_RUNNING);
	}

	/**
	 * Starts the game, setting parameters for the current difficulty.
	 */
	public void doStart() {
		synchronized (mSurfaceHolder) {
			mLastTime = System.currentTimeMillis() + 100;
			setState(STATE_RUNNING);
		}
	}

	/**
	 * Pauses the physics update & animation.
	 */
	public void pause() {
		synchronized (mSurfaceHolder) {
			if (mState == STATE_RUNNING)
				setState(STATE_PAUSE);
		}
	}

	/**
	 * Restores game state from the indicated Bundle. Typically called when the
	 * Activity is being restored after having been previously destroyed.
	 * 
	 * @param savedState
	 *            Bundle containing the game state
	 */
	public synchronized void restoreState(Bundle savedState) {
		synchronized (mSurfaceHolder) {
			setState(STATE_PAUSE);

			mDifficulty = savedState.getInt(KEY_DIFFICULTY);
			numSprites = savedState.getInt(KEY_WINS);
		}
	}

	public void clearSprites() {
		synchronized (mSprites) {
			mSprites.clear();
		}
	}

	private void initChessBoard() {
		mchChessBoard = new Chess();
		Bitmap mBitmap = BitmapFactory.decodeResource(res,
				R.drawable.chessboard);
		mchChessBoard.Initialize(mBitmap);
		mchChessBoard.setHeight(402);
		mchChessBoard.setWidth(402);
		mchChessBoard.setLeft(39);
		mchChessBoard.setTop(200);
	}

	private void initBackGround() {
		mBackground = new Chess();
		Bitmap mBitmap = BitmapFactory.decodeResource(res,
				R.drawable.background);
		mBackground.Initialize(mBitmap);
		mBackground.setHeight(800);
		mBackground.setWidth(480);
		mBackground.setLeft(0);
		mBackground.setTop(0);
	}

	/**
	 * Khoi tao cac quan co tren ban co Neu A[i][j] khong co quan co nao thi no
	 * se co gia tri la Null
	 */
	private void InitItems() {
		this.mPieces = new ArrayList<Piece>();
		Position mPoTemp = null;
		Bitmap bmblue = BitmapFactory.decodeResource(res, R.drawable.blue);
		Bitmap bmred = BitmapFactory.decodeResource(res, R.drawable.red);
		for (int i = 0; i < 5; i++)
			for (int j = 0; j < 5; j++) {
				Piece temp = new Piece();
				for (Position p : mPositions) {
					if (p.getX() == i && p.getY() == j)
						mPoTemp = new Position(p);
				}
				int index = 5 * i + j;
				if (i != 0 && j != 0 && i != 4 && j != 4) {
				} else if (index <= 10) {
					temp.setIndex(1);
<<<<<<< .mine
					temp.Initialize(bmred, 40, 40, 24, 1, true);
					temp.setPosition(mPoTemp);
					mPieces.add(temp);
=======
					mItems.add(temp);
>>>>>>> .r17
				} else {
					temp.setIndex(0);
<<<<<<< .mine
					temp.Initialize(bmblue, 40, 40, 24, 1, true);
					temp.setPosition(mPoTemp);
					mPieces.add(temp);
=======
					mItems.add(temp);
>>>>>>> .r17
				}
			}
	}
}
